package com.smzd.framework.config.handlers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.savedrequest.SavedRequest;

import com.smzd.framework.utils.JsonHelper;

public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        SavedRequest req = (SavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        String redirectUrl = null;
        if (req != null) {
            redirectUrl = req.getRedirectUrl();
        } else {
            redirectUrl = request.getContextPath();
            if (redirectUrl.length() == 1) {
                redirectUrl = "";
            }
        }
        String method = request.getParameter("_method");
        boolean json = method != null && "json".equalsIgnoreCase(method);
        if (json) {
            String contentType = "application/json";
            response.setContentType(contentType);
            PrintWriter out = response.getWriter();
            out.print(JsonHelper.getFailJsonString("redirect_url", redirectUrl,
                    exception == null ? "认证失败！" : exception.getMessage()));
            out.flush();
            out.close();
        } else {
            request.setAttribute("redirect_url", redirectUrl);
            super.onAuthenticationFailure(request, response, exception);
        }
    }

}
